package httpHandle

import (
	"encoding/json"
	"fmt"

	"github.com/TarsCloud/TarsGo/tars"
	"github.com/gin-gonic/gin"
	hypernexusApp "github.com/wzh200x/hyperNexus/hyperNexusApp"
	hypernexusType "github.com/wzh200x/hyperNexus/hyperNexusType"
	"github.com/wzh200x/webServer/config"
	"github.com/wzh200x/webServer/constants"
	"github.com/wzh200x/webServer/middleware/response"
	Server "github.com/wzh200x/webServer/server"
)

// PlatformReportRequest 平台上报请求结构
type PlatformReportRequest struct {
	Platform   int32    `json:"platform" form:"platform" binding:"required"`     // 平台类型
	AppId      string   `json:"appId" form:"appId" binding:"required"`           // 应用ID
	ReportType int32    `json:"reportType" form:"reportType" binding:"required"` // 上报类型
	Keys       []string `json:"keys" form:"keys" binding:"required"`             // 参数键
	Values     []string `json:"values" form:"values" binding:"required"`         // 参数值
}

// PlatformReportMessage 平台上报消息结构，与reportServer中的结构保持一致
type PlatformReportMessage struct {
	Platform     int32             `json:"platform"`     // 平台类型
	ReportType   int32             `json:"reportType"`   // 上报类型
	PlatformArgs map[string]string `json:"platformArgs"` // 平台参数
	ReportInfo   map[string]string `json:"reportInfo"`   // 上报信息
}

// HandlePlatformReport 处理平台上报请求
func HandlePlatformReport(c *gin.Context) {
	success, err := response.GetResponseFuncs(c)

	// 解析请求参数
	var req PlatformReportRequest
	if bindErr := c.ShouldBind(&req); bindErr != nil {
		err(constants.ErrUnknown, "无效的请求参数: "+bindErr.Error())
		return
	}

	// 验证keys和values数组长度是否一致
	if len(req.Keys) != len(req.Values) {
		err(constants.ErrUnknown, "参数键值对数量不匹配")
		return
	}

	// 构建平台参数和上报信息
	platformArgs := make(map[string]string)
	reportInfo := make(map[string]string)

	// 将keys和values数组转换为map
	for i, key := range req.Keys {
		// 简单处理：假设前缀为"p_"的键为平台参数，其他为上报信息
		if len(key) > 2 && key[:2] == "p_" {
			platformArgs[key[2:]] = req.Values[i] // 去掉前缀
		} else {
			reportInfo[key] = req.Values[i]
		}
	}
	// 填充平台配置参数
	platformInfo := config.GetPlatformAppConfig(int(req.Platform), req.AppId)
	if platformInfo == nil {
		err(constants.ErrAuth, "不支持的平台类型")
		return
	}
	// 填充appId
	platformArgs["appId"] = platformInfo.AppID
	// 填充appSecret
	platformArgs["appSecret"] = platformInfo.AppSecret
	// 填充privateKey
	platformArgs["privateKey"] = platformInfo.PrivateKey
	// 填充publicKey
	platformArgs["publicKey"] = platformInfo.PublicKey

	// 构建上报消息
	message := PlatformReportMessage{
		Platform:     req.Platform,
		ReportType:   req.ReportType,
		PlatformArgs: platformArgs,
		ReportInfo:   reportInfo,
	}

	// 序列化消息
	msgData, jsonErr := json.Marshal(message)
	if jsonErr != nil {
		err(constants.ErrUnknown, "序列化消息失败: "+jsonErr.Error())
		return
	}

	// 获取NATS客户端
	natsClient := Server.ServerApp.NatsClientIns
	if natsClient == nil {
		err(constants.ErrUnknown, "NATS客户端未初始化")
		return
	}

	// 发布消息到platformReport主题
	pubErr := natsClient.Publish("platformReport_"+hypernexusApp.GHyperNexusApp.ProjectName, msgData)
	if pubErr != nil {
		tars.GetLogger("").Errorf("发布平台上报消息失败: %v", pubErr)
		err(constants.ErrUnknown, "发布消息失败: "+pubErr.Error())
		return
	}

	// 记录日志
	tars.GetLogger("").Infof("已发送平台上报消息: 平台=%s, 类型=%s",
		hypernexusType.GetPlatformName(int(req.Platform)),
		hypernexusType.GetReportTypeName(int(req.ReportType)))

	// 返回成功
	success(map[string]interface{}{
		"message": fmt.Sprintf("平台上报消息已发送: %s - %s",
			hypernexusType.GetPlatformName(int(req.Platform)),
			hypernexusType.GetReportTypeName(int(req.ReportType))),
	})
}
